import datetime
import hashlib
import secrets

import django.utils.timezone as timezone
from django.core.validators import RegexValidator
from django.db import models
from rest_framework import serializers

from common.utils.encrypt import md5
from common.utils.token import create_token
import re


class BaseModel(models.Model):
    """
    基础模型，包含创建时间和更新时间字段
    """
    is_delete = models.IntegerField("数据逻辑状态", choices=((1, "无效"), (0, "有效")), default=0)
    pt_flag = models.IntegerField("压测标志", choices=((1, "压测数据"), (0, "正常数据")), default=0)
    create_time = models.DateTimeField("创建时间", default=timezone.now)
    update_time = models.DateTimeField("更新时间", auto_now=True, null=True, blank=True)

    class Meta:
        abstract = True  # 表示这是一个抽象类，不会生成对应的表
        ordering = ['-create_time']


class BaseSortModel(BaseModel):
    sort_num = models.SmallIntegerField("排序号", default=0)
    CHOICES_STATUS = ((0, "关闭"), (1, "开启"))
    is_active = models.SmallIntegerField("状态", choices=CHOICES_STATUS, default=1)

    class Meta:
        abstract = True
        ordering = ["-create_time"]

class Wechat(BaseSortModel):
    name = models.CharField('模板标题',max_length=20,help_text="模板标题（唯一标识）")
    wx_app_id = models.CharField('开发者账号', max_length=128, help_text="WXAPPID", default="")
    wx_app_secret = models.CharField('开发者密码', max_length=128, help_text="WXAPPSECRET", default="")
    description = models.TextField('描述说明',blank=True,default="",help_text="模板的详细用途说明")

    class Meta:
        db_table = 'wechat'
        verbose_name = '微信订阅号'
        verbose_name_plural = verbose_name
        ordering = ['-create_time']  # 默认按名称排序

    def __str__(self):
        return f"{self.name} (wx_app_id: {self.wx_app_id} wx_app_secret: {self.wx_app_secret}))"



class WechatTemplate(BaseSortModel):
    name = models.CharField('模板标题',max_length=20,help_text="模板标题（唯一标识）")
    wx_app_id = models.CharField('WXAPPID', max_length=128, help_text="WXAPPID", default="")
    wx_app_secret = models.CharField('WXAPPSECRET', max_length=128, help_text="WXAPPSECRET", default="")
    # 微信模板ID专业定义（带格式验证）
    template_id = models.CharField(
        "微信模板ID",
        max_length=128,  # 微信模板ID实际最大长度通常为128字符
        validators=[
            RegexValidator(
                regex='^[a-zA-Z0-9_-]{10,64}$',
                message='必须是10-64位字母/数字/下划线/横线组成的微信模板ID'
            )
        ],
        help_text="微信官方提供的模板ID，如：HzvBOeBKgqSDi_jfvyFt_O5SyP7Sv3_whbAlR7qukX0"
    )
    template_data = models.TextField('模板变量', blank=True, default="", help_text="JSON格式的模板变量数据")
    description = models.TextField('描述说明',blank=True,default="",help_text="模板的详细用途说明")

    class Meta:
        db_table = 'wechat_template'
        verbose_name = '微信模板消息'
        verbose_name_plural = verbose_name
        ordering = ['-create_time']  # 默认按名称排序

    def __str__(self):
        return f"{self.name} (ID: {self.template_id})"


class WechatOpenid(BaseSortModel):
    """客户信息表"""
    wechat_name = models.CharField("微信公众号名", max_length=64,default="")
    name = models.CharField("姓名", max_length=64,default="")
    phone = models.CharField("手机号", max_length=64, unique=True, default="")
    openid = models.CharField("openid", max_length=128, default="")
    description = models.TextField('描述说明', blank=True, default="", help_text="详细用途说明")

    class Meta:
        db_table = "wechat_openid"

    def __str__(self):
        return "手机号: {phone},微信Openid: {openid}".format(phone=self.phone, openid=self.openid)


class WechatLog(BaseModel):
    wechat_name = models.CharField("微信公众号名", max_length=64, default="")
    phone = models.CharField('手机号', max_length=20, help_text="发送的手机号")
    openid = models.CharField('微信公众openid', max_length=64, help_text="微信公众openid")
    template_id = models.CharField('模板CODE', max_length=128, help_text="模板CODE")
    send_time = models.DateTimeField("发送时间", default=timezone.now)
    content = models.CharField('短信内容', max_length=1024, help_text="短信内容")
    is_send = models.IntegerField("发送状态", choices=((0, "失败"), (1, "成功")), default=1)

    class Meta:
        db_table = 'wechat_log'
        verbose_name = '微信公众号发送记录'
        verbose_name_plural = verbose_name
        ordering = ['-create_time']  # 默认按名称排序

    def __str__(self):
        return f"{self.phone} (ID: {self.content})"